import {
  getQuizDetail,
  subComment,
  delMyComment,
  collectMjDetail,
  getGood,
} from "@/static/js/quiz.js";
import moment from "moment";
import { baseUrl } from "@/utils/baseUrl.js";
import { appJumpWx, formatTime } from "@/utils/utils.js";
import { completeTask } from '@/static/js/points.js';
export default {
  data() {
    return {
      appJumpWx,
      baseUrl,
      showMore: false,
      // 更多菜单
      menuList: [
        {
          icon: "/static/img/exchange/wx.png",
          name: "微信好友",
          remark: "",
          url: "",
          handler: "shareToWx",
        },
        {
          icon: `/static/img/exchange/collect_0.png`,
          name: "收藏",
          remark: "",
          url: "",
          handler: "collectDetail",
        },
      ],
      answerId: "",
      collectShow: true,
      allNewList: [],
      supplementList: [], //补充列表
      imgList: [],
      commentContent: "",
      delShow: false,
      delItem: {},
      commentShow: false,
      labelList: [],
      quizObj: {},
      commentList: [],
      mainData: {}, //数据大对象
      supplementList: [],

      getAvatar: (senderUserID) => {
        if (senderUserID == this.quizObj.ans_uid) {
          return this.mainData.ans_uid.avatar;
        } else {
          return this.mainData.uid.avatar;
        }
      },
      getNickname: (senderUserID) => {
        if (senderUserID == this.quizObj.ans_uid) {
          return this.mainData.ans_uid.nickname;
        } else {
          return this.mainData.uid.nickname;
        }
      },
      showPointsTips: false,
      pointsObj: {},
    };
  },
  onLoad(e) {
    this.answerId = e.id;
    this.getMjDetail();
    this.completeQuest('A5');
  },
  onShow() { },

  watch: {
    commentContent(val) {
      if (val !== "") {
        this.commentShow = true;
      } else {
        this.commentShow = false;
      }
    },
  },

  methods: {
    // 去主页
    go(id) {
      let userInfo = uni.getStorageSync("userInfo");
      if (userInfo.id == id) {
        uni.navigateTo({
          url: "/pages/my/homeCenter/home",
        });
        return;
      } else {
        uni.navigateTo({
          url: "/pages/my/homeCenter/taHome?id=" + id,
        });
      }
    },
    //给头像补充前缀
    addUrlAvatar(url) {
      if (url != null && url != undefined && url != "") {
        if (url.indexOf("http") == -1) {
          return (url = "https://api.xiaozhucaishui.com" + url);
        } else {
          return url;
        }
      }
    },
    //获取问答详情
    async getMjDetail() {
      const obj = { quiz_id: this.answerId, status: 3 };
      const res = await getQuizDetail(obj);

      if (res.code === 1) {
        this.mainData = res.data;
        this.quizObj = res.data.quiz;
        this.commentList = res.data.comment;
        this.menuList[1].icon = `/static/img/exchange/collect_${res.data.quiz.is_collect}.png`;

        if (res.data.quiz.info_images) {
          this.imgList = res.data.quiz.info_images.split(",");
        }

        if (res.data.quiz.label_id) {
          this.labelList = res.data.quiz.label_name.split(",");
        }

        const arr = res.data.chatroomtext.map((val) => {
          const json = JSON.parse(val.message);
          return {
            createTime: val.createtime ? formatTime(val.createtime * 1000, 'Y-M-D H:m:s') : '',
            message: json,
            userId: val.user_id,
            msgRevoke: val.is_revoke,
            is_supplement: val.is_supplement,
          };
        });

        this.allNewList = arr.filter(item => item.message.message && item.is_supplement !== 1);
        this.supplementList = arr.filter(item => item.message.message && item.is_supplement === 1);
      }
    },

    //预览图片
    viewImg(val) {
      uni.previewImage({
        urls: [val],
      });
    },

    // 分享弹出弹窗
    actionClick() {
      this.showMore = true;
    },

    //弹窗按钮操作
    menuClick(item) {
      if (item.handler) {
        this[item.handler]();
      } else if (item.url) {
        this.$tools.href(item.url);
      }
    },

    //评论框聚焦显示
    focusText() {
      this.collectShow = false;
    },

    //评论框失焦显示
    blurText() {
      if (this.commentContent !== "") {
        this.collectShow = false;
      } else {
        this.collectShow = true;
      }
    },

    //发布评论
    postComment() {
      let obj = {
        quiz_id: this.answerId,
        content: this.commentContent,
      };
      subComment(obj).then((res) => {
        if (res.code == 1) {
          this.commentContent = "";
          this.collectShow = true;
          this.$tools.showToast(res.msg);
          this.getMjDetail();
        }
      });
    },

    //删除我的评论
    delCommentShow(item) {
      this.delShow = true;
      this.delItem = item;
    },

    delComment() {
      let obj = {
        comment_id: this.delItem.id,
      };
      delMyComment(obj).then((res) => {
        if (res.code == 1) {
          uni.showToast({
            title: "删除成功",
            icon: "none",
          });
          this.delShow = false;
          this.getMjDetail();
        }
      });
    },

    //收藏回答
    collectDetail() {
      let obj = {
        quiz_id: this.answerId,
      };
      collectMjDetail(obj).then((res) => {
        if (res.code == 1) {
          this.quizObj.is_collect = 1 - this.quizObj.is_collect;
          this.menuList[1].icon = `/static/img/exchange/collect_${this.quizObj.is_collect}.png`;
          if (this.quizObj.is_collect == 1) {
            this.$tools.showToast("收藏成功");
          } else if (this.quizObj.is_collect == 0) {
            this.$tools.showToast("取消收藏");
          }
        }
      });
    },

    //点赞
    likeCount(val) {
      let obj = {
        commentid: val.id,
      };
      getGood(obj).then((res) => {
        if (res.code == 1) {
          this.getMjDetail();
        }
      });
    },

    //分享到微信好友
    shareToWx(callback) {
      // 准备分享内容
      const shareContent = {
        id: "gh_54c7ed1b5bfc",
        path: `/pagesAsk/answerDetail/index?id=${this.answerId}`,
        webUrl: `${this.baseUrl}/h5/#/pages/downLoad/downLoad`,
      };

      // 准备小程序分享对象
      const miniProgramShareObj = {
        provider: "weixin",
        scene: "WXSceneSession", // 分享到微信好友
        type: 5, // 分享类型（这里为小程序类型）
        miniProgram: shareContent,
        imageUrl: "/static/logo-min.png", // 图片地址
        title: this.quizObj.title, // 标题
      };

      // 调用微信分享API
      uni.share(miniProgramShareObj, {
        success(res) {
          if (typeof callback === 'function') {
            callback(); // 成功回调
          }
          this.showMore = false; // 隐藏更多内容（假设场景）
        },
        fail(err) {
          console.error("分享失败:", JSON.stringify(err)); // 输出错误信息
        },
      });
    },


    //完成任务
    completeQuest(code) {
      completeTask({ code }).then(res => {
        if (res.code == 1) {
          setTimeout(() => {
            this.showPointsTips = true;
          }, 1000);
          this.pointsObj = res.data;
        }
      })
      setTimeout(() => {
        this.showPointsTips = false;
      }, 3000);
    },
  },
};